#include "threadPool.h"
#include "msgHandler.h"
#include "login.h"
#include "dirStack.h"
#include "cmdHandler.h"

int makeWorker(threadPool_t *pthreadPool) {
    for(int i = 0; i < pthreadPool->workerNum; ++i) {
        pthread_create(&pthreadPool->tidArr[i], NULL, threadFunc, pthreadPool);
    }
    return 0;
}

void *threadFunc(void *arg) {
    threadPool_t *pthreadPool = (threadPool_t *)arg;
    while(1) {
        pthread_mutex_lock(&pthreadPool->mutex);
        while(pthreadPool->taskQueue.queueSize == 0) {
            pthread_cond_wait(&pthreadPool->cond, &pthreadPool->mutex);
        }
        printf("tid = %ld, worker thread got a task\n", pthread_self());
        int netfd = pthreadPool->taskQueue.pFront->netfd;
        pthread_mutex_unlock(&pthreadPool->mutex);

        // 0.接收消息
        train_t train;
        bzero(&train, sizeof(train_t));
        
        // 1.登录验证
        while(1) {
            int ret = recv_msg(netfd, &train);
            if(ret == 0){
                close(netfd);
                pthread_exit(NULL);
            }
            user_t userInfo;        
            memcpy(&userInfo, train.data, train.length);
            if(!login(netfd, &userInfo)) {
                break;
            }
        }

        // 2.初始化工作目录
        dirStack_t dirStack;
        char path[] = "./zs";
        initStack(&dirStack, path);

        // 3.处理命令
        while(1) {
            int ret = recv_msg(netfd, &train);
            if(ret == 0) {
                close(netfd);
                pthread_exit(NULL);
            }
            cmd_t cmdInfo;
            memcpy(&cmdInfo, train.data, train.length);
            /* printf("cmd = %s, args = %s, len = %d\n", cmdInfo.cmd, cmdInfo.args, train.length); */
            handleCmd(netfd, &train, &dirStack);
        }

        close(netfd);
    }

    pthread_exit(NULL);
}

